import re
from json import dumps
from enetity_extraction.test import get_extraction_results


def validate_court_name(article_sections, extract_sections):
    # extraction_results = get_extraction_results(file_path)
    courts = extract_sections.get('法院名称', [])
    court_names = [court['match'] for court in courts if 'match' in court]
    # court_names = [
    #     "贵州遵义汇川人民法院",
    #     "贵州省遵义汇川人民法院",
    #     "贵州省贵阳铁路运输法院",
    #     "贵阳铁路运输法院"
    # ]
    # 专门法院名称后缀
    specialized_court_suffixes = ['铁路运输法院', '军事法院', '海事法院', '知识产权法院']
    errors = []
    for court_name in court_names:
        start = next((item['start_pos'] for item in courts if item.get('match') == court_name), "")
        end = next((item['end_pos'] for item in courts if item.get('match') == court_name), "")
        paragraph_index = next((item['paragraph_index'] for item in courts if item.get('match') == court_name), "")
        # 检查是否是专门法院
        if court_name.endswith(tuple(specialized_court_suffixes)):
            # 专门法院不应冠以省市区名称
            if re.search(r'省|市|区', court_name):
                # 提取专门法院名称部分
                # correct_name = re.sub(r'省|市|区', '', court_name).strip()
                error = {
                    "correct": "",
                    "desc": "",
                    "end": end,
                    "exception": "False",
                    "explain": "专门法院名称无需冠以省、自治区、直辖市的名称。",
                    "label": "",
                    "label_type": "",
                    "offset": len(court_name),
                    "opt": "",
                    "ppl": "",
                    "pre_insert": "",
                    "source": "",
                    "start": start,
                    "tag": "",
                    "text": "",
                    "type": "法院名称校验",
                    "url": "",
                    "word": "",
                    "paragraph_index": paragraph_index
                }
                errors.append(error)
        else:
            # 普通法院名称应符合规范格式
            pattern = ''
            if '市' in court_name:
                pattern = r'^[\u4e00-\u9fa5]*(?:省[\u4e00-\u9fa5]*)?市[\u4e00-\u9fa5]*(?:区[\u4e00-\u9fa5]*)?(?:(基层|中级|高级))人民法院$'
            else:
                pattern = r'^[\u4e00-\u9fa5]*(?:省[\u4e00-\u9fa5]*)?州[\u4e00-\u9fa5]*(?:区[\u4e00-\u9fa5]*)?(?:(基层|中级|高级))人民法院$'
            correct_court_pattern = re.compile(pattern)
            # correct_court_pattern = re.compile(r'^[\u4e00-\u9fa5]*(?:省[\u4e00-\u9fa5]*(?:市[\u4e00-\u9fa5]*|州))?区人民法院$')
            if not correct_court_pattern.match(court_name):
                error = {
                    "correct": '示例："XX省XX市XX区人民法院"',
                    "desc": "",
                    "end": end,
                    "exception": "False",
                    "explain": "基层人民法院、中级人民法院名称前应冠以省、自治区、直辖市的名称。",
                    "label": 2,
                    "label_type": 0,
                    "offset": len(court_name),
                    "opt": "",
                    "ppl": "",
                    "pre_insert": 1,
                    "source": "",
                    "start": start,
                    "tag": "",
                    "text": "",
                    "type": "法院名称校验",
                    "url": "",
                    "word": court_name,
                    "paragraph_index": paragraph_index
                }
                errors.append(error)
    # 如果存在错误信息，则返回错误信息
    return {"data": errors}

def validate_court_name_new(article_sections, extract_sections):
    # 初始化一个列表来存储法院名称
    court_names = []
    # 读取文件内容
    with open('logic_rule/data/all_court_name.txt', 'r', encoding='utf-8') as file:
        for line in file:
            # 去掉行尾的换行符和多余的空格
            line = line.strip()
            # 分割行内容，假设法院名称和缩写之间用制表符或多个空格分隔
            parts = line.split()
            if parts:
                # 添加法院名称到列表中
                court_names.append(parts[0])
    # extraction_results = get_extraction_results(file_path)
    courts = extract_sections.get('法院名称', [])
    extract_court_names = [court['match'] for court in courts if 'match' in court]
    errors = []
    for court_name in extract_court_names:
        start = next((item['start_pos'] for item in courts if item.get('match') == court_name), "")
        end = next((item['end_pos'] for item in courts if item.get('match') == court_name), "")
        paragraph_index = next((item['paragraph_index'] for item in courts if item.get('match') == court_name), "")
        court_name = court_name.replace('\r', '')
        if court_name not in court_names:
            error = {
                "correct": "",
                "desc": "",
                "end": end,
                "exception": "False",
                "explain": "",
                "label": "",
                "label_type": "",
                "offset": len(court_name),
                "opt": "",
                "ppl": "",
                "pre_insert": "",
                "source": "",
                "start": start,
                "tag": "",
                "text": "",
                "type": f"{court_name}，法院名称错误",
                "url": "",
                "word": "",
                # "paragraph_index": paragraph_index
            }
            errors.append(error)

    # 如果存在错误信息，则返回错误信息
    return {"data": errors}

if __name__ == "__main__":
    # 示例使用
    court_names = [
        "贵州遵义汇川人民法院",
        "贵州省遵义汇川人民法院",
        "贵州省贵阳铁路运输法院",
        "贵阳铁路运输法院"
    ]
    filename = '/Users/hoyo/PycharmProjects/judicial_document_proofreading/enetity_extraction/0725_test_data/2-贵州林荣资产管理有限公司与刘正超、周相波民间借贷纠纷一审民事案141382473.txt'
    # 对每个法院名称进行校验
    result = validate_court_name(filename)


    # 打印结果
    print(result)